package com.thread;

/**
 * @author :admin
 * @description: 实现线程通信方式一：使用同步关键词
 * 解释：由于线程A和线程B持有同一个MyObject类的对象object，尽管这两个线程需要调用不同的方法，但是它们是同步执行的，
 * 比如：线程B需要等待线程A执行完了methodA()方法之后，它才能执行methodB()方法。这样，线程A和线程B就实现了通信。
 * 这种方式，本质上就是“共享内存”式的通信。多个线程需要访问同一个共享变量，谁拿到了锁（获得了访问权限），谁就可以执行。
 * @create date: 2019/4/20 12:07
 */
public class ThreadNotifyDemo1 {

    public static void main(String[] args){
        NotifyObject notifyObject=new NotifyObject();
        Thread thread1=new Thread(() -> notifyObject.printA(),"thread1");
        Thread thread2=new Thread(() -> notifyObject.printB(),"thread2");
        Thread thread3=new Thread(new Runnable() {
            @Override
            public void run() {
                notifyObject.printC();
            }
        },"thread3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class NotifyObject{
    synchronized void printA(){
        try {
            for (int i = 0; i < 5; i++) {
                Thread.sleep(1000);
                System.out.println("name:"+Thread.currentThread().getName()+" i="+i);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    synchronized void printB(){
        try {
            for (int i = 0; i < 5; i++) {
                Thread.sleep(1000);
                System.out.println("name:"+Thread.currentThread().getName()+" i="+i);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    synchronized public void printC() {
        try {
            for (int i = 0; i < 5; i++) {
                Thread.sleep(1000);
                System.out.println("name:"+Thread.currentThread().getName()+" i="+i);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

